<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | 王勇程 <laughskydragon@qq.com>                         |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

/**
 * 用户业务逻辑
 */
class User extends LogicBase
{

    
    /**
     * 获取用户信息
     */
    public function getUserInfo($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        $user = $this->modelUser->getInfo(['id' => $userId]);
        if (!$user) {
            return [RESULT_ERROR, '用户不存在'];
        }
        
        // 检测并更新VIP状态
        $this->checkAndUpdateVipStatus($userId);
        
        // 重新获取用户信息（可能已更新VIP状态）
        $user = $this->modelUser->getInfo(['id' => $userId]);
        
        // 格式化返回数据
        $userInfo = [
            'id' => $user['id'],
            'nickname' => $user['nickname'],
            'avatar' => $user['avatar_id'] > 0 ? get_picture_url($user['avatar_id']) : $user['avatar_url'],
            'avatar_id' => $user['avatar_id'],
            'mobile' => $user['mobile'],
            'invite_code' => $user['invite_code'],
            'inviter_id' => $user['inviter_id'],
            'vip_level' => $user['vip_level'],
            'vip_level_text' => $this->getVipLevelText($user['vip_level']),
            'vip_start_time' => $user['vip_start_time'],
            'vip_expire_time' => $user['vip_expire_time'],
            'is_vip' => $user['vip_level'] > 0 && $user['vip_expire_time'] > time(),
            'vip_remaining_days' => $this->getVipRemainingDays($user),
            'total_earnings' => $user['total_earnings'],
            'available_amount' => $user['available_amount'],
            'total_points' => $user['total_points'],
            'status' => $user['status'],
            'status_text' => $this->getStatusText($user['status']),
            'create_time' => $user['create_time'],
            'last_login_time' => $user['last_login_time'],
        ];
        
        return $userInfo;
    }
    
    /**
     * 检测并更新用户VIP状态
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function checkAndUpdateVipStatus($userId)
    {
        try {
            $user = $this->modelUser->getInfo(['id' => $userId]);
            if (!$user) {
                return false;
            }
            
            // 如果用户是VIP且已过期
            if ($user['vip_level'] > 0 && $user['vip_expire_time'] > 0 && $user['vip_expire_time'] < time()) {
                // 记录VIP过期日志
                \think\facade\Log::info('用户VIP过期自动降级', [
                    'user_id' => $userId,
                    'old_vip_level' => $user['vip_level'],
                    'expire_time' => date('Y-m-d H:i:s', $user['vip_expire_time']),
                    'current_time' => date('Y-m-d H:i:s')
                ]);
                
                // 降级为普通用户
                $result = $this->modelUser->updateInfo(['id' => $userId], [
                    'vip_level' => 0,
                    'update_time' => time()
                ]);
                
                if ($result) {
                    // 发送VIP过期通知
                    $this->sendVipExpiredMessage($userId);
                    
                    // 记录操作日志
                    action_log('VIP过期', '用户VIP自动过期降级，user_id：' . $userId);
                }
                
                return $result;
            }
            
            return true;
            
        } catch (\Exception $e) {
            \think\facade\Log::error('VIP状态检测异常：' . $e->getMessage(), [
                'user_id' => $userId,
                'trace' => $e->getTraceAsString()
            ]);
            return false;
        }
    }
    
    /**
     * 获取VIP剩余天数
     */
    private function getVipRemainingDays($user)
    {
        if ($user['vip_level'] == 0 || $user['vip_expire_time'] <= time()) {
            return 0;
        }
        
        $now = time();
        $expireTime = $user['vip_expire_time'];
        $remainingSeconds = $expireTime - $now;
        
        return max(0, ceil($remainingSeconds / (24 * 60 * 60)));
    }

    /**
     * 获取VIP等级文本
     */
    private function getVipLevelText($vipLevel)
    {
        $vipLevelTexts = [
            0 => '普通用户',
            1 => '月卡VIP',
            2 => '季卡VIP', 
            3 => '年卡VIP'
        ];
        
        return $vipLevelTexts[$vipLevel] ?? '普通用户';
    }

    /**
     * 获取状态文本
     */
    private function getStatusText($status)
    {
        $statusTexts = [
            0 => '禁用',
            1 => '正常'
        ];
        
        return $statusTexts[$status] ?? '未知';
    }
    
    /**
     * 生成邀请码
     */
    public function generateInviteCode()
    {
        do {
            $code = strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8));
        } while ($this->modelUser->getInfo(['invite_code' => $code]));
        
        return $code;
    }
    

    
    /**
     * 发送VIP过期消息
     * @author 王勇程 <laughskydragon@qq.com>
     */
    private function sendVipExpiredMessage($userId)
    {
        try {
            $this->modelMessage->insertGetId([
                'user_id' => $userId,
                'type' => 'system',
                'title' => 'VIP会员已过期',
                'content' => '您的VIP会员已过期，已自动降级为普通用户。如需继续享受VIP特权，请及时续费。',
                'is_read' => 0,
                'create_time' => time(),
                'update_time' => time()
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('发送VIP过期消息失败：' . $e->getMessage());
        }
    }
    
    /**
     * 获取用户统计信息
     */
    private function getUserStats($userId)
    {
        // 关注商品数量
        $followCount = $this->modelUserFollow->stat(['user_id' => $userId]);
        
        // 签到统计
        $checkinStats = $this->modelCheckinRecord->getCheckinStats($userId);
        
        // 邀请统计
        $inviteCount = $this->modelUser->stat(['inviter_id' => $userId]);
        
        // 订单统计
        $orderStats = $this->modelVipOrder->getInviteEarnings($userId);
        
        // 提现统计
        $withdrawStats = $this->modelWithdrawOrder->getWithdrawStats($userId);
        
        // 未读消息数量
        $unreadCount = $this->modelMessage->getUnreadCount($userId);
        
        return [
            'follow_count' => $followCount,
            'checkin_stats' => $checkinStats,
            'invite_count' => $inviteCount,
            'order_stats' => $orderStats,
            'withdraw_stats' => $withdrawStats,
            'unread_count' => $unreadCount
        ];
    }
    
    /**
     * 更新用户信息
     */
    public function updateUserInfo($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        // 过滤允许更新的字段
        $allowFields = ['nickname', 'avatar_url', 'avatar_id', 'gender', 'city', 'province', 'birthday', 'bio'];
        $updateData = [];
        
        foreach ($allowFields as $field) {
            if (isset($data[$field])) {
                $updateData[$field] = $data[$field];
            }
        }
        // 保持avatar_id为数据库字段
        
        if (empty($updateData)) {
            return [RESULT_ERROR, '没有可更新的数据'];
        }
        
        $result = $this->modelUser->updateInfo(['id' => $userId], $updateData);
        
        return $result ? [RESULT_SUCCESS, '更新成功'] : [RESULT_ERROR, '更新失败'];
    }
    
    /**
     * 获取邀请列表
     */
    public function getInviteList($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        $page = $data['page'] ?? 1;
        $limit = $data['limit'] ?? 20;
        
        $list = $this->modelUser->getList([
            'inviter_id' => $userId
        ], 'id,nickname,avatar_url,create_time', 'create_time desc', [
            'list_rows' => $limit,
            'page' => $page
        ]);
        
        return $list;
    }
    
    /**
     * HTTP GET请求
     */
    private function httpGet($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        
        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200 && $result) {
            return json_decode($result, true);
        }
        
        return false;
    }
    
    /**
     * 获取用户列表搜索条件
     */
    public function getWhere($data = [])
    {
        $where = [];
        
        // 搜索条件：用户名、昵称、手机号
        !empty($data['search_data']) && $where['nickname|phone'] = ['like', '%'.$data['search_data'].'%'];
        
        // VIP等级筛选
        isset($data['vip_level']) && $data['vip_level'] !== '' && $where['vip_level'] = $data['vip_level'];
        
        // VIP用户筛选（用于后台首页"VIP用户数"链接）
        if (isset($data['is_vip']) && $data['is_vip'] == 1) {
            $where['vip_level'] = ['>', 0];
            $where['vip_expire_time'] = ['>', date('Y-m-d H:i:s')];
        }
        
        // 状态筛选
        isset($data['status']) && $data['status'] !== '' && $where['status'] = $data['status'];
        
        // 注册时间范围 - 修复：使用create_time而不是register_time
        !empty($data['start_time']) && $where['create_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['create_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日新增用户筛选（用于后台首页"今日新增用户"链接）
        if (!empty($data['create_time']) && is_string($data['create_time'])) {
            $date = $data['create_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['create_time'] = ['between', [$startTime, $endTime]];
        }
        
        // 活跃用户筛选（用于后台首页"活跃用户数"链接）
        // 这里定义活跃用户为最近7天内有登录记录的用户
        if (isset($data['is_active']) && $data['is_active'] == 1) {
            $sevenDaysAgo = strtotime('-7 days');
            $where['last_login_time'] = ['>', $sevenDaysAgo];
        }
        
        return $where;
    }

    /**
     * 获取提现订单搜索条件
     */
    public function getWithdrawOrderWhere($data = [])
    {
        $where = [];
        
        // 用户ID搜索
        !empty($data['user_id']) && $where['user_id'] = $data['user_id'];
        
        // 提现单号搜索
        !empty($data['withdraw_no']) && $where['withdraw_no'] = ['like', '%' . $data['withdraw_no'] . '%'];
        
        // 提现状态搜索
        isset($data['withdraw_status']) && $data['withdraw_status'] !== '' && $where['withdraw_status'] = $data['withdraw_status'];
        
        // 提现类型搜索
        !empty($data['withdraw_type']) && $where['withdraw_type'] = $data['withdraw_type'];
        
        // 金额范围搜索
        !empty($data['min_amount']) && $where['amount'] = ['>=', $data['min_amount']];
        !empty($data['max_amount']) && $where['amount'] = ['<=', $data['max_amount']];
        
        // 申请时间范围搜索
        !empty($data['start_time']) && $where['apply_time'] = ['>=', strtotime($data['start_time'])];
        !empty($data['end_time']) && $where['apply_time'] = ['<=', strtotime($data['end_time'])];
        
        // 今日数据筛选
        if (!empty($data['apply_time']) && is_string($data['apply_time'])) {
            $date = $data['apply_time'];
            $startTime = strtotime($date . ' 00:00:00');
            $endTime = strtotime($date . ' 23:59:59');
            $where['apply_time'] = ['between', [$startTime, $endTime]];
        }
        
        return $where;
    }
    
    /**
     * 获取用户列表
     */
    public function getUserList($where = [], $field = true, $order = 'create_time desc', $paginate = DB_LIST_ROWS)
    {
        // 排除已删除的用户
        $where[DATA_STATUS_NAME] = ['neq', DATA_DELETE];
        
        return $this->modelUser->getList($where, $field, $order, $paginate);
    }
    
    /**
     * 用户添加
     */
    public function userAdd($data = [])
    {
        // 验证数据
        $validate_result = $this->validateUser->scene('add')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateUser->getError()];
        }
        
        // 处理数据
        $data['create_time'] = time();
        $data['update_time'] = time();
        $data['invite_code'] = $this->generateInviteCode();
        
        $result = $this->modelUser->setInfo($data);
        
        $result && action_log('新增', '用户新增，nickname：' . $data['nickname']);
        
        return $result ? [RESULT_SUCCESS, '用户添加成功'] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 用户编辑
     */
    public function userEdit($data = [])
    {
        $validate_result = $this->validateUser->scene('edit')->check($data);
        if (!$validate_result) {
            return [RESULT_ERROR, $this->validateUser->getError()];
        }
        
        $data['update_time'] = time();
        
        $result = $this->modelUser->setInfo($data);
        
        $result && action_log('编辑', '用户编辑，id：' . $data['id']);
        
        return $result ? [RESULT_SUCCESS, '用户编辑成功'] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 用户删除
     */
    public function userDel($data = [])
    {
        $where = ['id' => $data['id']];
        
        $result = $this->modelUser->deleteInfo($where);
        
        $result && action_log('删除', '用户删除，id：' . $data['id']);
        
        return $result ? [RESULT_SUCCESS, '用户删除成功'] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 用户状态切换
     */
    public function userStatus($data = [])
    {
        $where = ['id' => $data['id']];
        $update = ['status' => $data['status'], 'update_time' => time()];
        
        $result = $this->modelUser->updateInfo($where, $update);
        
        $result && action_log('状态', '用户状态切换，id：' . $data['id'] . '，status：' . $data['status']);
        
        return $result ? [RESULT_SUCCESS, '状态切换成功'] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 用户导出
     */
    public function exportUserList($where = [])
    {
        $list = $this->getUserList($where, true, 'create_time desc', false);
        
        // 导出逻辑
        // TODO: 实现Excel导出功能
        
        return [RESULT_SUCCESS, '导出成功'];
    }
    
    /**
     * 用户VIP管理
     */
    public function userVipManage($data = [])
    {
        $userId = $data['id'];
        $vipLevel = $data['vip_level'] ?? 0;
        $startTime = $data['vip_start_time'] ?? null;
        $expireTime = $data['vip_expire_time'] ?? null;
        
        // 转换时间格式为时间戳
        if ($startTime) {
            $startTime = strtotime($startTime);
        }
        if ($expireTime) {
            $expireTime = strtotime($expireTime);
        }
        
        // 使用模型的updateVipInfo方法
        $result = $this->modelUser->updateVipInfo($userId, $vipLevel, $startTime, $expireTime);
        
        $result && action_log('VIP管理', '用户VIP管理，id：' . $userId . '，VIP等级：' . $vipLevel);
        
        return $result ? [RESULT_SUCCESS, 'VIP管理成功'] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 购买VIP
     */
    public function purchaseVip($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $vipLevel = $data['vip_level'] ?? 0;
        
        if (!$userId) {
            return [RESULT_ERROR, '用户ID不能为空'];
        }
        
        if (!in_array($vipLevel, [1, 3, 12])) {
            return [RESULT_ERROR, 'VIP等级无效'];
        }
        
        // 获取当前用户信息
        $user = $this->modelUser->getInfo(['id' => $userId]);
        if (!$user) {
            return [RESULT_ERROR, '用户不存在'];
        }
        
        // 计算VIP时间
        $startTime = date('Y-m-d H:i:s');
        
        // 如果用户已经是VIP且未过期，从过期时间开始计算
        if ($user['vip_level'] > 0 && $user['vip_expire_time'] && $user['vip_expire_time'] > $startTime) {
            $startTime = $user['vip_expire_time'];
        }
        
        // 更新VIP信息
        $result = $this->modelUser->updateVipInfo($userId, $vipLevel, $startTime);
        
        if ($result) {
            // 记录VIP购买日志
            action_log('VIP购买', '用户购买VIP，user_id：' . $userId . '，VIP等级：' . $vipLevel);
            
            // 发送VIP购买成功消息
            $this->sendVipPurchaseMessage($userId, $vipLevel);
        }
        
        return $result ? [RESULT_SUCCESS, 'VIP购买成功'] : [RESULT_ERROR, 'VIP购买失败'];
    }
    
    /**
     * 检查并处理过期VIP用户
     */
    public function checkExpiredVip()
    {
        $processedCount = $this->modelUser->processExpiredVip();
        
        if ($processedCount > 0) {
            \think\facade\Log::info("处理过期VIP用户：{$processedCount}个");
        }
        
        return [RESULT_SUCCESS, "处理完成，共处理{$processedCount}个过期VIP用户"];
    }
    
    /**
     * 获取VIP状态信息
     */
    public function getVipStatus($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        if (!$userId) {
            return null; // 查询方法返回null表示查询失败
        }
        
        $user = $this->modelUser->getInfo(['id' => $userId]);
        if (!$user) {
            return null; // 查询方法返回null表示查询失败
        }
        
        $vipStatus = [
            'is_vip' => $user['vip_level'] > 0,
            'vip_level' => $user['vip_level'],
            'vip_level_text' => $this->getVipLevelText($user['vip_level']),
            'vip_start_time' => $user['vip_start_time'],
            'vip_expire_time' => $user['vip_expire_time'],
            'is_expired' => false,
            'remaining_days' => 0
        ];
        
        if ($user['vip_level'] > 0) {
            $userModel = new \app\common\model\User($user);
            $vipStatus['is_expired'] = $userModel->isVipExpired();
            $vipStatus['remaining_days'] = $userModel->getVipRemainingDays();
        }
        
        return $vipStatus; // 直接返回数据，参考Article模块模式
    }
    
    /**
     * 发送VIP购买成功消息
     */
    private function sendVipPurchaseMessage($userId, $vipLevel)
    {
        try {
            $levelTexts = [1 => '一个月VIP', 3 => '三个月VIP', 12 => '一年VIP'];
            $levelText = $levelTexts[$vipLevel] ?? 'VIP';
            
            $this->modelMessage->insertGetId([
                'user_id' => $userId,
                'type' => 'vip',
                'title' => 'VIP购买成功',
                'content' => "恭喜您成功购买{$levelText}，享受专属特权！",
                'is_read' => 0,
                'create_time' => time(),
                'update_time' => time()
            ]);
        } catch (\Exception $e) {
            \think\facade\Log::error('发送VIP购买消息失败：' . $e->getMessage());
        }
    }
    
    /**
     * 用户积分管理
     */
    public function userPointsManage($data = [])
    {
        $userId = $data['id'];
        $points = $data['points'];
        $type = $data['type']; // add 或 subtract
        $description = $data['description'] ?? '管理员操作';
        
        $user = $this->modelUser->getInfo(['id' => $userId]);
        if (!$user) {
            return [RESULT_ERROR, '用户不存在'];
        }
        
        $newPoints = $type == 'add' ? $user['total_points'] + $points : $user['total_points'] - $points;
        $newPoints = max(0, $newPoints); // 积分不能为负数
        
        // 更新用户积分
        $result = $this->modelUser->updateInfo(['id' => $userId], [
            'total_points' => $newPoints,
            'update_time' => time()
        ]);
        
        if ($result) {
            // 记录积分变动
            $this->modelPointsRecord->insertGetId([
                'user_id' => $userId,
                'type' => $type == 'add' ? 'admin_add' : 'admin_subtract',
                'points' => $type == 'add' ? $points : -$points,
                'description' => $description,
                'create_time' => time(),
                'update_time' => time()
            ]);
            
            action_log('积分管理', '用户积分管理，id：' . $userId . '，操作：' . $type . '，积分：' . $points);
        }
        
        return $result ? [RESULT_SUCCESS, '积分管理成功'] : [RESULT_ERROR, $this->modelUser->getError()];
    }
    
    /**
     * 检查商品关注状态
     */
    public function checkFollowStatus($data = [])
    {
        $userId = $data['user_id'] ?? 0;
        $productId = $data['product_id'] ?? 0;
        
        if (!$userId || !$productId) {
            return null;
        }
        
        // 检查是否已关注
        $followInfo = $this->modelUserFollow->getInfo([
            'user_id' => $userId,
            'product_id' => $productId,
            'status' => 1
        ]);
        
        $isFollowed = !empty($followInfo);
        
        return [
            'is_followed' => $isFollowed,
            'product_id' => $productId
        ];
    }

    /**
     * 获取即将过期的VIP用户
     */
    public function getVipUsersNearExpire($data = [])
    {
        try {
            $days = $data['days'] ?? 3;
            
            $startTime = time();
            $endTime = time() + ($days * 86400);
            
            $where = [
                'vip_level' => ['>', 0],
                'vip_expire_time' => ['between', [$startTime, $endTime]]
            ];
            
            $list = $this->modelUser->getList($where, 'id,nickname,vip_level,vip_expire_time', '', false);
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 发送VIP过期提醒消息
     */
    public function sendVipExpireMessage($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $remainingDays = $data['remaining_days'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $user = $this->modelUser->getInfo(['id' => $userId]);
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            // 检查是否已经发送过相同的提醒（避免重复发送）
            $today = date('Y-m-d');
            $existingMessage = $this->modelMessage->getInfo([
                'user_id' => $userId,
                'type' => 'vip_expire',
                'create_time' => ['>=', strtotime($today . ' 00:00:00')],
                'content' => ['like', "%{$remainingDays}天%"]
            ]);
            
            if ($existingMessage) {
                return [RESULT_SUCCESS, '提醒已发送过，不重复发送'];
            }
            
            $vipLevelText = $user['vip_level_text'] ?? 'VIP';
            
            if ($remainingDays == 1) {
                $title = 'VIP即将过期提醒';
                $content = "您的{$vipLevelText}将在明天过期，请及时续费以继续享受VIP特权！";
            } else {
                $title = 'VIP过期提醒';
                $content = "您的{$vipLevelText}将在{$remainingDays}天后过期，请及时续费以继续享受VIP特权！";
            }
            
            // 插入消息记录
            $messageData = [
                'user_id' => $userId,
                'type' => 'vip_expire',
                'title' => $title,
                'content' => $content,
                'extra_data' => [
                    'remaining_days' => $remainingDays,
                    'vip_level' => $user['vip_level'],
                    'expire_time' => $user['vip_expire_time']
                ]
            ];
            
            $result = $this->modelMessage->sendMessage($messageData);
            
            if ($result) {
                \think\facade\Log::info("VIP过期提醒发送成功，用户ID：{$userId}，剩余天数：{$remainingDays}");
                return [RESULT_SUCCESS, 'VIP过期提醒发送成功'];
            } else {
                return [RESULT_ERROR, 'VIP过期提醒发送失败'];
            }
            
        } catch (\Exception $e) {
            \think\facade\Log::error("发送VIP过期提醒失败，用户ID：{$userId}，错误：" . $e->getMessage());
            return [RESULT_ERROR, '发送VIP过期提醒失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取VIP过期状态详情
     */
    public function getVipExpireStatus($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $user = $this->modelUser->getInfo(['id' => $userId]);
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            $status = [
                'user_id' => $userId,
                'is_vip' => false,
                'vip_level' => $user['vip_level'],
                'vip_level_text' => $user['vip_level_text'] ?? '普通用户',
                'vip_start_time' => $user['vip_start_time'],
                'vip_expire_time' => $user['vip_expire_time'],
                'is_expired' => false,
                'is_expiring_soon' => false,
                'remaining_days' => 0,
                'remaining_hours' => 0,
                'expire_warning' => ''
            ];
            
            if ($user['vip_level'] > 0 && $user['vip_expire_time']) {
                $now = time();
                $expireTime = strtotime($user['vip_expire_time']);
                
                if ($expireTime > $now) {
                    $status['is_vip'] = true;
                    $remainingSeconds = $expireTime - $now;
                    $status['remaining_days'] = ceil($remainingSeconds / 86400);
                    $status['remaining_hours'] = ceil($remainingSeconds / 3600);
                    
                    // 判断是否即将过期（3天内）
                    if ($status['remaining_days'] <= 3) {
                        $status['is_expiring_soon'] = true;
                        if ($status['remaining_days'] == 1) {
                            $status['expire_warning'] = '您的VIP将在明天过期，请及时续费！';
                        } else {
                            $status['expire_warning'] = "您的VIP将在{$status['remaining_days']}天后过期，请及时续费！";
                        }
                    }
                } else {
                    $status['is_expired'] = true;
                    $status['expire_warning'] = '您的VIP已过期，请续费以继续享受VIP特权！';
                }
            }
            
            return [RESULT_SUCCESS, '获取成功', $status];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 批量处理VIP过期提醒
     */
    public function batchSendVipExpireReminders($data = [])
    {
        try {
            $results = [
                'total_sent' => 0,
                'reminders_3_days' => 0,
                'reminders_1_day' => 0,
                'errors' => []
            ];
            
            // 发送3天过期提醒
            $users3DaysResult = $this->getVipUsersNearExpire(['days' => 3]);
            if ($users3DaysResult[0] == RESULT_SUCCESS) {
                $users3Days = $users3DaysResult[2];
                foreach ($users3Days as $user) {
                    $sendResult = $this->sendVipExpireMessage([
                        'user_id' => $user['id'],
                        'remaining_days' => 3
                    ]);
                    
                    if ($sendResult[0] == RESULT_SUCCESS) {
                        $results['reminders_3_days']++;
                        $results['total_sent']++;
                    } else {
                        $results['errors'][] = "用户ID {$user['id']} 3天提醒发送失败：{$sendResult[1]}";
                    }
                }
            }
            
            // 发送1天过期提醒
            $users1DayResult = $this->getVipUsersNearExpire(['days' => 1]);
            if ($users1DayResult[0] == RESULT_SUCCESS) {
                $users1Day = $users1DayResult[2];
                foreach ($users1Day as $user) {
                    $sendResult = $this->sendVipExpireMessage([
                        'user_id' => $user['id'],
                        'remaining_days' => 1
                    ]);
                    
                    if ($sendResult[0] == RESULT_SUCCESS) {
                        $results['reminders_1_day']++;
                        $results['total_sent']++;
                    } else {
                        $results['errors'][] = "用户ID {$user['id']} 1天提醒发送失败：{$sendResult[1]}";
                    }
                }
            }
            
            return [RESULT_SUCCESS, '批量发送完成', $results];
            
        } catch (\Exception $e) {
            \think\facade\Log::error('批量发送VIP过期提醒失败：' . $e->getMessage());
            return [RESULT_ERROR, '批量发送失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 处理VIP过期用户
     */
    public function processExpiredVip($data = [])
    {
        try {
            $expiredUsers = $this->modelUser->getList([
                'vip_level' => ['>', 0],
                'vip_expire_time' => ['<=', time()]
            ]);
            
            $processedCount = 0;
            foreach ($expiredUsers as $user) {
                $updateResult = $this->modelUser->updateInfo(['id' => $user['id']], [
                    'vip_level' => 0,
                    'vip_start_time' => 0,
                    'vip_expire_time' => 0,
                    'update_time' => time()
                ]);
                
                if ($updateResult) {
                    $processedCount++;
                }
            }
            
            return [RESULT_SUCCESS, "处理完成，共处理{$processedCount}个过期VIP用户", ['processed_count' => $processedCount]];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '处理VIP过期用户失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 增加用户收益
     */
    public function addUserEarnings($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $amount = $data['amount'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            if ($amount <= 0) {
                return [RESULT_ERROR, '收益金额必须大于0'];
            }
            
            $result = $this->modelUser->where('id', $userId)
                ->inc('total_earnings', $amount)
                ->inc('available_amount', $amount)
                ->update();
            
            if ($result) {
                return [RESULT_SUCCESS, '收益增加成功'];
            } else {
                return [RESULT_ERROR, '收益增加失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '收益增加失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 减少可提现金额
     */
    public function reduceAvailableAmount($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $amount = $data['amount'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            if ($amount <= 0) {
                return [RESULT_ERROR, '金额必须大于0'];
            }
            
            // 先获取当前金额
            $user = $this->modelUser->getInfo(['id' => $userId], 'available_amount');
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            $newAmount = $user['available_amount'] - $amount;
            if ($newAmount < 0) {
                return [RESULT_ERROR, '可提现金额不足'];
            }
            
            $result = $this->modelUser->updateInfo(['id' => $userId], ['available_amount' => $newAmount]);
            
            if ($result) {
                return [RESULT_SUCCESS, '可提现金额减少成功'];
            } else {
                return [RESULT_ERROR, '可提现金额减少失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '可提现金额减少失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 增加用户积分
     */
    public function addUserPoints($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $points = $data['points'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            if ($points <= 0) {
                return [RESULT_ERROR, '积分必须大于0'];
            }
            
            // 先获取当前积分
            $user = $this->modelUser->getInfo(['id' => $userId], 'total_points');
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            $newPoints = $user['total_points'] + $points;
            $result = $this->modelUser->updateInfo(['id' => $userId], ['total_points' => $newPoints]);
            
            if ($result) {
                return [RESULT_SUCCESS, '积分增加成功'];
            } else {
                return [RESULT_ERROR, '积分增加失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '积分增加失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 减少用户积分
     */
    public function reduceUserPoints($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $points = $data['points'] ?? 0;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            if ($points <= 0) {
                return [RESULT_ERROR, '积分必须大于0'];
            }
            
            // 先获取当前积分
            $user = $this->modelUser->getInfo(['id' => $userId], 'total_points');
            if (!$user) {
                return [RESULT_ERROR, '用户不存在'];
            }
            
            $newPoints = $user['total_points'] - $points;
            if ($newPoints < 0) {
                return [RESULT_ERROR, '积分不足'];
            }
            
            $result = $this->modelUser->updateInfo(['id' => $userId], ['total_points' => $newPoints]);
            
            if ($result) {
                return [RESULT_SUCCESS, '积分减少成功'];
            } else {
                return [RESULT_ERROR, '积分减少失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '积分减少失败：' . $e->getMessage()];
        }
    }

    /**
     * 根据提现单号获取订单
     */
    public function getWithdrawByNo($data = [])
    {
        try {
            $withdrawNo = $data['withdraw_no'] ?? '';
            
            if (empty($withdrawNo)) {
                return [RESULT_ERROR, '提现单号不能为空'];
            }
            
            $order = $this->modelWithdrawOrder->getInfo(['withdraw_no' => $withdrawNo]);
            
            if (!$order) {
                return [RESULT_ERROR, '提现订单不存在'];
            }
            
            return [RESULT_SUCCESS, '获取成功', $order];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取用户提现记录
     */
    public function getUserWithdrawOrders($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $withdrawStatus = $data['withdraw_status'] ?? null;
            $page = $data['page'] ?? 1;
            $limit = $data['limit'] ?? 20;
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            $where = ['user_id' => $userId];
            
            if ($withdrawStatus !== null) {
                $where['withdraw_status'] = $withdrawStatus;
            }
            
            $paginate = ['list_rows' => $limit, 'page' => $page];
            $list = $this->modelWithdrawOrder->getList($where, true, 'id desc', $paginate);
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 更新提现状态
     */
    public function updateWithdrawStatus($data = [])
    {
        try {
            $withdrawId = $data['withdraw_id'] ?? 0;
            $withdrawStatus = $data['withdraw_status'] ?? '';
            $paymentNo = $data['payment_no'] ?? '';
            $failReason = $data['fail_reason'] ?? '';
            
            if (!$withdrawId) {
                return [RESULT_ERROR, '提现订单ID不能为空'];
            }
            
            if ($withdrawStatus === '') {
                return [RESULT_ERROR, '提现状态不能为空'];
            }
            
            $updateData = [
                'withdraw_status' => $withdrawStatus,
                'process_time' => time(),
                'update_time' => time()
            ];
            
            if ($paymentNo) {
                $updateData['payment_no'] = $paymentNo;
            }
            
            if ($failReason) {
                $updateData['fail_reason'] = $failReason;
            }
            
            $result = $this->modelWithdrawOrder->updateInfo(['id' => $withdrawId], $updateData);
            
            if ($result) {
                return [RESULT_SUCCESS, '提现状态更新成功'];
            } else {
                return [RESULT_ERROR, '提现状态更新失败'];
            }
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '提现状态更新失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取提现统计
     */
    public function getWithdrawStatistics($data = [])
    {
        try {
            $userId = $data['user_id'] ?? null;
            $startTime = $data['start_time'] ?? null;
            $endTime = $data['end_time'] ?? null;
            
            $where = ['withdraw_status' => 2]; // 只统计已完成的提现
            
            if ($userId) {
                $where['user_id'] = $userId;
            }
            
            if ($startTime && $endTime) {
                $where['process_time'] = ['between', [$startTime, $endTime]];
            }
            
            $totalAmount = $this->modelWithdrawOrder->stat($where, 'sum', 'actual_amount') ?: 0;
            $totalCount = $this->modelWithdrawOrder->stat($where, 'count') ?: 0;
            
            $statistics = [
                'total_amount' => $totalAmount,
                'total_count' => $totalCount,
                'average_amount' => $totalCount > 0 ? round($totalAmount / $totalCount, 2) : 0
            ];
            
            return [RESULT_SUCCESS, '获取成功', $statistics];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 获取待处理提现订单
     */
    public function getPendingWithdraws($data = [])
    {
        try {
            $limit = $data['limit'] ?? 50;
            
            $where = ['withdraw_status' => 0];
            $paginate = ['list_rows' => $limit];
            
            $list = $this->modelWithdrawOrder->getList($where, true, 'id asc', $paginate);
            
            return [RESULT_SUCCESS, '获取成功', $list];
            
        } catch (\Exception $e) {
            return [RESULT_ERROR, '获取失败：' . $e->getMessage()];
        }
    }
    
    /**
     * 检查用户状态
     * @author 王勇程 <laughskydragon@qq.com>
     */
    public function checkUserStatus($data = [])
    {
        try {
            $userId = $data['user_id'] ?? 0;
            $lastLoginIp = $data['last_login_ip'] ?? '';
            
            if (!$userId) {
                return [RESULT_ERROR, '用户ID不能为空'];
            }
            
            // 更新用户最后登录时间和IP
            $updateData = [
                'last_login_time' => time(),
                'update_time' => time()
            ];
            
            if (!empty($lastLoginIp)) {
                $updateData['last_login_ip'] = $lastLoginIp;
            }
            
            $result = $this->modelUser->updateInfo(['id' => $userId], $updateData);
            
            if (!$result) {
                return [RESULT_ERROR, '更新登录信息失败'];
            }
            
            // 检测并更新VIP状态
            $this->checkAndUpdateVipStatus($userId);
            
            // 获取用户最新信息
            $userInfo = $this->getUserInfo(['user_id' => $userId]);
            
            if (is_array($userInfo) && isset($userInfo[0]) && $userInfo[0] == RESULT_SUCCESS) {
                return [RESULT_SUCCESS, '状态检查完成', $userInfo[2]];
            } else {
                // 如果getUserInfo返回的不是标准格式，直接返回
                return [RESULT_SUCCESS, '状态检查完成', $userInfo];
            }
            
        } catch (\Exception $e) {
            \think\facade\Log::error('检查用户状态失败：' . $e->getMessage(), [
                'user_id' => $userId,
                'trace' => $e->getTraceAsString()
            ]);
            return [RESULT_ERROR, '状态检查失败：' . $e->getMessage()];
        }
    }

}
